// receiver.c
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <mqueue.h>
#include <time.h>
#include <string.h>

#define QUEUE_NAME  "/test_queue1"
#define MAX_SIZE    1024
#define MSG_STOP    "exit"

int main() {
    mqd_t mq;
    char buffer[MAX_SIZE];
    struct timespec start_time, end_time;
    double latency;

    // 打开消息队列
    mq = mq_open(QUEUE_NAME, O_RDONLY);
    if (mq == -1) {
        perror("mq_open");
        exit(1);
    }

    printf("Receiver started. Waiting for messages...\n");

    while (1) {
        if (mq_receive(mq, (char *)&start_time, sizeof(start_time), NULL) == -1) {
            perror("mq_receive");
            exit(1);
        }

        if (mq_receive(mq, buffer, MAX_SIZE, NULL) == -1) {
            perror("mq_receive");
            exit(1);
        }

        // 记录接收时间
        clock_gettime(CLOCK_MONOTONIC, &end_time);

        latency = (end_time.tv_sec - start_time.tv_sec) * 1e3 + 
                  (end_time.tv_nsec - start_time.tv_nsec) / 1e6;

        printf("Received message: %s\n", buffer);
        printf("Latency: %.3f ms\n", latency);

        if (strcmp(buffer, MSG_STOP) == 0)
            break;
    }

    // 关闭消息队列
    if (mq_close(mq) == -1) {
        perror("mq_close");
        exit(1);
    }

    // 删除消息队列
    if (mq_unlink(QUEUE_NAME) == -1) {
        perror("mq_unlink");
        exit(1);
    }

    return 0;
}
